﻿using CarPCBATest.Procedure;
using Common;
using ImageSourceModuleCs;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using VM.Core;
using VMControls.WPF.Release;

namespace CarPCBATest.ViewModel
{
    public partial class HomeViewModel
    {
        private int highBrightness = 0xff;
        private int midBrightness = 140;
        private int lowBrightness = 85;
        private const int pcbCount = 4;
        private const int turnLedIndex = 3;

        public VmRenderControl control;
        private uint currentProcId = 0;
        private Stopwatch swGlobal = new Stopwatch();

        private void SetTestResult(bool isTurnLed, bool isOk, string msg)
        {
            for (int i = 0; i < pcbCount; i++)
            {
                if (isTurnLed)
                {
                    if (i > 0 && i < turnLedIndex)        //跳过 1 2 3
                    {
                        continue;
                    }
                }
                else
                {
                    if (i >= turnLedIndex)    //跳过4 5 6
                    {
                        break;
                    }
                }
                if (!isOk)
                {
                    TestResultDatas[i].IsOK = false;
                }
                TestResultDatas[i].NgMsg.Add(msg);
            }
        }

        private bool S12L_Stop(LedCurrentConfig config)
        {
            //切换电压
            Global.IT6302.SetCurrent(config.TestCurrent, config.TestCurrent, 2);
            Global.IT6302.SetVoltage(config.TestVoltage, config.TestVoltage, 5);
            Global.IT6302.SetOutputStatus(true);
            Thread.Sleep(100);
            currentProcId = config.ProcID;
            Log = $"开始测试{config.LedDesc}功能";

            bool comRet = true;
            Thread.Sleep(1000);
            // 1.4测试电流
            double current = 0;
            try
            {
                current = Global.IT6302.MeasCurrent(1) * 1000;
            }
            catch
            {
                current = Global.IT6302.MeasCurrent(1) * 1000;
            }

            Log = $"功能{config.LedDesc}电流为{current}mA";

            if (current <= config.UpperLimitCurrent & current >= config.LowerLimitCurrent)
            {
                // ok
                Log = "电流在OK范围";
                SetTestResult(false, true, $"功能[{config.LedDesc}] 电流=[{current}mA] OK");
            }
            else
            {
                //ng
                Log = "电流不在OK范围";
                SetTestResult(false, false, $"功能[{config.LedDesc}] 电流=[{current}mA] NG");

                comRet = false;
            }
            bool timeOut = false;
            vmProcHaveExec = false;
            swGlobal.Restart();
            vmResult1 = null;
            Application.Current.Dispatcher.Invoke(() =>
            {
                VisionTool.SetProcVisionRet(config.ProcName, control);
            });
            // 2.视觉检测 sdk获取图像
            CameraTool.Open();
            var image = CameraTool.GetCurrentImage();
            //设置到图像源
            ImageSourceModuleTool imageSourceModuleTool = (ImageSourceModuleTool)VmSolution.Instance[$"{config.ProcName}.图像源1"];
            imageSourceModuleTool.SetImageData(image);

            Task.Run(() =>
            {
                Thread.Sleep(3000);
                timeOut = true;
            });

            VisionTool.RunProc(config.ProcName);

            while (!timeOut)
            {
                if (vmProcHaveExec)
                {
                    break;
                }
                Thread.Sleep(10);
            }
            if (timeOut)
            {
                // 超时
                Log = "视觉判定流程执行超时";

                SetTestResult(false, false, $"功能[{config.LedDesc}] 视觉判定流程执行超时");

                comRet = false;
            }
            if (vmResult2 is null || vmResult3 is null)
            {
                Log = "功能[{config.LedDesc}] 视觉判定测试结果为null";

                SetTestResult(false, false, $"功能[{config.LedDesc}] 视觉判定测试结果为null");
            }
            if (vmResult2 == "1" && vmResult3 == "1")
            {
                // ok
                Log = $"功能{config.LedDesc}视觉测试OK";
                SetTestResult(false, true, $"功能{config.LedDesc}视觉测试OK");
            }
            else
            {
                SetTestResult(false, false, $"功能[{config.LedDesc}] 灯光视觉判定NG");

                //ng
                Log = $"{config.LedDesc}视觉测试NG";
                comRet = false;
            }
            return comRet;
        }

        private bool S12L_Turn(LedCurrentConfig config)
        {
            //切换电压
            Global.IT6302.SetCurrent(config.TestCurrent, config.TestCurrent, 2);
            Global.IT6302.SetVoltage(config.TestVoltage, config.TestVoltage, 5);
            Global.IT6302.SetOutputStatus(true);
            currentProcId = config.ProcID;
            Log = $"开始测试{config.LedDesc}功能";

            bool comRet = true;
            Thread.Sleep(1000);
            // 1.4测试电流
            double current = 0;
            try
            {
                current = Global.IT6302.MeasCurrent(1) * 1000;
            }
            catch
            {
                current = Global.IT6302.MeasCurrent(1) * 1000;
            }

            Log = $"功能{config.LedDesc}电流为{current}mA";
            //LocalLogs.Add(Log);
            if (current <= config.UpperLimitCurrent & current >= config.LowerLimitCurrent)
            {
                // ok
                Log = "电流在OK范围";
                SetTestResult(true, true, $"功能[{config.LedDesc}] 电流=[{current}mA] OK");
            }
            else
            {
                //ng
                Log = "电流不在OK范围";
                SetTestResult(true, false, $"功能[{config.LedDesc}] 电流=[{current}mA] NG");

                comRet = false;
            }
            bool timeOut = false;
            vmProcHaveExec = false;
            swGlobal.Restart();
            vmResult1 = null;
            Application.Current.Dispatcher.Invoke(() =>
            {
                VisionTool.SetProcVisionRet(config.ProcName, control);
            });
            // 2.视觉检测 sdk获取图像
            CameraTool.Open();
            var image = CameraTool.GetCurrentImage();

            //设置到图像源
            ImageSourceModuleTool imageSourceModuleTool = (ImageSourceModuleTool)VmSolution.Instance[$"{config.ProcName}.图像源1"];
            imageSourceModuleTool.SetImageData(image);

            Task.Run(() =>
            {
                Thread.Sleep(3000);
                timeOut = true;
            });

            VisionTool.RunProc(config.ProcName);
            while (!timeOut)
            {
                if (vmProcHaveExec)
                {
                    break;
                }
                Thread.Sleep(10);
            }
            if (timeOut)
            {
                // 超时
                Log = "视觉判定流程执行超时";
                SetTestResult(true, false, $"功能[{config.LedDesc}] 视觉判定流程执行超时");

                comRet = false;
            }
            if (vmResult4 is null)
            {
                SetTestResult(true, false, $"功能[{config.LedDesc}] 视觉判定测试结果为null");

                Log = "视觉判定测试结果为null";
            }
            if (vmResult4 == "1")
            {
                // ok
                SetTestResult(true, true, $"功能{config.LedDesc}视觉测试OK");

                Log = $"功能{config.LedDesc}视觉测试OK";
            }
            else
            {
                //ng
                Log = $"{config.LedDesc}视觉测试NG";

                SetTestResult(true, false, $"功能[{config.LedDesc}] 灯光视觉判定NG");

                comRet = false;
            }
            return comRet;
        }

        // 刹车灯

        public bool Stop_Low(LedCurrentConfig config)
        {
            Global.CANfd.StopLedLightness = lowBrightness;
            Global.CANfd.TurnRightLedLightness = 0;
            Global.CANfd.TurnLeftLedLightness = 0;

            return S12L_Stop(config);
        }

        public bool Stop_Mid(LedCurrentConfig config)
        {
            Global.CANfd.StopLedLightness = midBrightness;
            Global.CANfd.TurnRightLedLightness = 0;
            Global.CANfd.TurnLeftLedLightness = 0;

            return S12L_Stop(config);
        }

        public bool Stop_High(LedCurrentConfig config)
        {
            Global.CANfd.StopLedLightness = highBrightness;
            Global.CANfd.TurnRightLedLightness = 0;
            Global.CANfd.TurnLeftLedLightness = 0;

            return S12L_Stop(config);
        }

        public bool TurnLeft_Low(LedCurrentConfig config)
        {
            try
            {
                Global.CANfd.StopLedLightness = 0;
                Global.CANfd.TurnRightLedLightness = 0;
                Global.CANfd.TurnLeftLedLightness = lowBrightness;

                var tmp = S12L_Turn(config);
                return tmp;
            }
            catch (Exception ex)
            {
                Log = ex.Message;
                Mylog.Error(ex, ex.Message);
                TestResultDatas[0].NgMsg.Add($"功能[{config.LedDesc}] {ex.Message}");
                return false;
            }
        }

        public bool TurnLeft_High(LedCurrentConfig config)
        {
            try
            {
                Global.CANfd.StopLedLightness = 0;
                Global.CANfd.TurnRightLedLightness = 0;
                Global.CANfd.TurnLeftLedLightness = highBrightness;

                var tmp = S12L_Turn(config);
                return tmp;
            }
            catch (Exception ex)
            {
                Log = ex.Message;
                Mylog.Error(ex, ex.Message);
                TestResultDatas[0].NgMsg.Add($"功能[{config.LedDesc}] {ex.Message}");
                return false;
            }
        }

        public bool TurnRight_Low(LedCurrentConfig config)
        {
            Global.CANfd.StopLedLightness = 0;
            Global.CANfd.TurnRightLedLightness = lowBrightness;
            Global.CANfd.TurnLeftLedLightness = 0;

            return S12L_Turn(config);
        }

        public bool TurnRight_High(LedCurrentConfig config)
        {
            Global.CANfd.StopLedLightness = 0;
            Global.CANfd.TurnRightLedLightness = highBrightness;
            Global.CANfd.TurnLeftLedLightness = 0;

            return S12L_Turn(config);
        }
    }
}